#include <iostream>
#include <vector>
#include <unistd.h>
#include "Mythread.hpp"
#include "RingQueue.hpp"
#include "Task.hpp"
#include <ctime>

using ringqueue_t = Ringqueue_t<int>;

void Consumer(ringqueue_t &rq, std::string name)
{
	while (true)
	{
		sleep(1);
		// 消费
		// Task t;
		int Data;
		rq.Pop(&Data);
		std::cout << "Consumer handler task: " << "[" << name << "]" << Data << std::endl;
		// 处理
		// t();
	}
}

void Producter(ringqueue_t &rq, std::string name)
{
	srand(time(nullptr) ^ pthread_self());
	int cnt = 6;
	while (true)
	{
		// 获取任务
		// 生产任务
		rq.Enqueue(cnt);
		std::cout << "Productor : " << "[" << name << "]" << cnt << std::endl;
		cnt++;
	}
}

void Initcomm(std::vector<Mythread::Thread<ringqueue_t>> *threads, int num, ringqueue_t &rq, Mythread::func_t<ringqueue_t> func, const std::string &who)
{
	for (int i = 0; i < num; i++)
	{
		std::string name = "thread-" + std::to_string(i + 1) + "-" + who;
		threads->emplace_back(func, rq, name); // 构造创建线程后存放到vector进行管理
	}
}

void InitProductor(std::vector<Mythread::Thread<ringqueue_t>> *threads, int num, ringqueue_t &rq) // num是创建的线程数
{
	Initcomm(threads, num, rq, Consumer, "Consumer");
}

void InitConsumer(std::vector<Mythread::Thread<ringqueue_t>> *threads, int num, ringqueue_t &rq)
{
	Initcomm(threads, num, rq, Producter, "Producter");
}

void StarAll(std::vector<Mythread::Thread<ringqueue_t>> &threads)
{
	for (auto &thread : threads)
	{
		thread.start();
	}
}

void WaitALL(std::vector<Mythread::Thread<ringqueue_t>> &threads)
{
	for (auto &thread : threads)
	{
		thread.join();
	}
}

int main()
{
	// 先创建一个环形队列对生产消费模型进行管理
	ringqueue_t *rq = new ringqueue_t(6);
	std::vector<Mythread::Thread<ringqueue_t>> threads;

	// 初始化（创建线程）
	InitProductor(&threads, 2, *rq);
	InitConsumer(&threads, 3, *rq);

	// 启动
	StarAll(threads);

	// 回收
	WaitALL(threads);
	return 0;
}